package com.brian.obsever.observer.runner;

import com.brian.obsever.observer.Observer;
import com.brian.obsever.observer.subject.impl.AlertSubject;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @program: base
 * @author: Brian Huang
 * @create: 2020-07-11 17
 **/
@Component
public class AlertRunner implements ApplicationRunner, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Autowired
    private AlertSubject alertSubject;

    /**
     * ApplicationRunner 在 IOC 加载完成后  会执行run方法
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 通过getBeansOfType 获取 Observer接口所有实现类
        Map<String, Observer> observers = applicationContext.getBeansOfType(Observer.class);
        // 注册观察者
        for(Observer observer: observers.values()){
            alertSubject.addObserver(observer);
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.applicationContext = applicationContext;
    }
}
